package com.kgcx.common.utils;

import com.kgcx.common.constant.Cons;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.*;

public class ValidateUtils {
    private static Logger logger = LoggerFactory.getLogger(ValidateUtils.class);

    public static String sortParam(Map<String, String[]> parameterMap) {
        if (MapUtils.isNotEmpty(parameterMap)) {
            List<String> paramList = new ArrayList<>();
            //把请求参数用key=value的方式组成字符串list
            parameterMap.forEach((k, v) -> {
                if (ArrayUtils.isNotEmpty(v)) {
                    for (String s : v) {
                        paramList.add(k.concat("=").concat(s));
                    }
                }
            });
            //按照首字母重新排序
            paramList.sort(String.CASE_INSENSITIVE_ORDER);
            //将排序好的list组合成以&分隔的整字符串
            return CollectionUtils.getAllString(paramList, "&");
        }
        return "";
    }

    public static String sortParamForFeign(Map<String, Collection<String>> parameterMap) {
        Map<String, String[]> map = new HashMap<>();
        if (MapUtils.isNotEmpty(parameterMap)) {
            parameterMap.forEach((k, v) -> map.put(k, v.toArray(new String[]{})));
        }
        return sortParam(map);
    }

    public static boolean validateSignature(String timestamp, String signature, Map<String, String[]> parameterMap) {
        String paramString = ValidateUtils.sortParam(parameterMap);

        logger.debug("paramString=" + paramString);
        String s = generateSignature(timestamp, paramString);
        logger.debug("signature=" + s);
        return signature.equalsIgnoreCase(s);
    }

    public static String generateSignature(String timestamp, String paramString) {
        return DigestUtils.md5Hex(Cons.MD5_KEY.concat(timestamp)
                .concat(paramString).getBytes(StandardCharsets.UTF_8));
    }
}
